package org.edu.modules.center.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.center.entity.VeStudyProgress;
import org.edu.modules.center.mapper.VeStudyProgressMapper;
import org.edu.modules.center.service.IVeStudyProgressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VeStudyProgressServiceImpl
        extends ServiceImpl<VeStudyProgressMapper, VeStudyProgress>
        implements IVeStudyProgressService
{
    @Autowired
    VeStudyProgressMapper veStudyProgressMapper;

    public List<VeStudyProgress> nodeList()
    {
        return this.veStudyProgressMapper.nodeList();
    }

    public JSONArray queryTree(Wrapper<VeStudyProgress> queryWrapper)
    {
        JSONObject json = new JSONObject();
        List<Map<String, Object>> list = this.veStudyProgressMapper.selectMaps(queryWrapper);
        JSONArray jArray = getChildren(list, Integer.valueOf(0));
        return jArray;
    }

    public Integer selectStudyTime(Map<String, Object> params)
    {
        return this.veStudyProgressMapper.selectStudyTime(params);
    }

    private JSONArray getChildren(List<Map<String, Object>> list, Object pid)
    {
        JSONArray jArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            if (((Map)list.get(i)).get("pid").equals(pid))
            {
                JSONObject jObj = new JSONObject(true);
                //lbh 2024/7/30 String k >>Object k
                for (Object k : ((Map)list.get(i)).keySet()) {
                    //lbh 2024/7/30 k >> k.toString
                    jObj.put(k.toString(), ((Map)list.get(i)).get(k));
                }
                JSONArray jArrayChild = getChildren(list, ((Map)list.get(i)).get("id"));
                if (jArrayChild.size() > 0) {
                    jObj.put("children", jArrayChild);
                }
                jArray.add(jObj);
                list.remove(i);
                i--;
            }
        }
        return jArray;
    }

    public int selectCount(String courseid, String studentid)
    {
        Map<String, Object> params = new HashedMap();
        LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        studentid = sysUser.getUserId().toString();
        params.put("courseid", courseid);
        params.put("studentid", studentid);

        return this.veStudyProgressMapper.selectCount(params).intValue();
    }
}
